package org.small.shop.phone.api.config.mybatis;

import java.io.IOException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
 * 
* @ClassName: MyBatisConfig
* @Description: 创建SqlSessionFactoryBean工厂类
* @author LYQ(廖先生)
* @date 2017年12月15日 上午1:52:59
*
 */
@Configuration
@PropertySource(value = {"classpath:mybatis.properties"}) // 加载配置文件
@EnableTransactionManagement
public class MyBatisConfig {
	// dao映射文件路径,可以有多个，在配置文件,隔开
	@Value("${mapperLocations}")
	private String mapperLocations;
	
	@Resource
	private DataSource dataSource;
	
	// @Bean(name="sqlSessionFactory")
	// 当前容器没有这个sqlSessionFactory的情况下创建
	@Bean
	@ConditionalOnMissingBean  
	public SqlSessionFactoryBean sqlSessionFactoryBean() {
		
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		
		sqlSessionFactoryBean.setDataSource(dataSource);
				
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		
		try {
			// 加载dao.xml配置文件的方式
			sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sqlSessionFactoryBean;
	}
	
}
